package com.cc.controller;

import com.cc.mapper.GoodMapper;
import com.cc.mapper.GoodsMapper;
import com.dy.cc.Good;
import com.dy.cc.Goods;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.kaoshi.common.config.Result;
import org.apache.http.HttpHost;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
@CrossOrigin
@RequestMapping("client")
public class ClientController {

    @Autowired
    private GoodMapper goodMapper;

    @Autowired
    private GoodsMapper goodsMapper;

    // 查询ES索引中所有数据
    @RequestMapping("findAll")
    public Result findAll() {
        try (RestHighLevelClient client = createClient()) {
            // 编写查询操作
            SearchRequest searchRequest = new SearchRequest("good");
            SearchSourceBuilder query = new SearchSourceBuilder().query(QueryBuilders.matchAllQuery());
            searchRequest.source(query);
            //发送请求
            SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
            SearchHits hits = response.getHits();
            // 提取查询结果
            List<Map<String, Object>> results = new ArrayList<>();
            for (SearchHit hit : hits) {
                Map<String, Object> sourceAsMap = hit.getSourceAsMap();
                results.add(sourceAsMap);
            }
            return Result.ok(results);
        } catch (IOException e) {
            e.printStackTrace();
            return Result.fail("Error searching Elasticsearch");
        }
    }

    // 根据外键查询ES索引中的数据
    @RequestMapping("findGoodsByForeignKey")
    public Result findGoodsByForeignKey(String id) {
        try (RestHighLevelClient client = createClient()) {
            // 编写查询操作
            SearchRequest searchRequest = new SearchRequest("goods");
            SearchSourceBuilder query = new SearchSourceBuilder()
                    .query(QueryBuilders.termQuery("uid", id));
            searchRequest.source(query);

            // 发送请求
            SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
            SearchHits hits = response.getHits();

            // 提取查询结果
            List<Map<String, Object>> results = new ArrayList<>();
            for (SearchHit hit : hits) {
                Map<String, Object> sourceAsMap = hit.getSourceAsMap();
                results.add(sourceAsMap);
            }

            if (!results.isEmpty()) {
                return Result.ok(results);
            } else {
                return Result.fail("Documents not found");
            }
        } catch (IOException e) {
            e.printStackTrace();
            return Result.fail("Error searching Elasticsearch");
        }
    }



    // 查询ES索引中所有数据
    @RequestMapping("findGoods")
    public Result findGoods() {
        try (RestHighLevelClient client = createClient()) {
            // 编写查询操作
            SearchRequest searchRequest = new SearchRequest("goods");
            SearchSourceBuilder query = new SearchSourceBuilder().query(QueryBuilders.matchAllQuery());
            query.from(0);  // 从第0条开始
            query.size(20); // 返回20条记录
            searchRequest.source(query);
            //发送请求
            SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
            SearchHits hits = response.getHits();
            // 提取查询结果
            List<Map<String, Object>> results = new ArrayList<>();
            for (SearchHit hit : hits) {
                Map<String, Object> sourceAsMap = hit.getSourceAsMap();
                results.add(sourceAsMap);
            }
            return Result.ok(results);
        } catch (IOException e) {
            e.printStackTrace();
            return Result.fail("Error searching Elasticsearch");
        }
    }


    // 创建Elasticsearch客户端
    private RestHighLevelClient createClient() {
        HttpHost httpHost = new HttpHost("127.0.0.1", 9200, "http");
        RestClientBuilder builder = RestClient.builder(httpHost);
        return new RestHighLevelClient(builder);
    }


    //获取goods数据库全部数据并添加到es文档
    @RequestMapping("findAddGoods")
    public Result<List<Goods>> findAddGoods(Goods goods) throws IOException {
        // 从数据库获取数据
        List<Goods> goodsList = goodsMapper.sousuo(goods);
        System.out.println("1111111111111111111111111111"+goodsList);
        //创建java和es的链接
        HttpHost httpHost = new HttpHost("127.0.0.1", 9200, "http");
        RestClientBuilder builder = RestClient.builder(httpHost);
        RestHighLevelClient client = new RestHighLevelClient(builder);
        System.out.println(client.indices());
        //指令方式: put /goods/_doc/1 {}
        IndexRequest indexRequest = new IndexRequest();
        // 创建IndexRequest并指定类型
        //IndexRequest indexRequest = new IndexRequest("your_index_name", "your_type_name");
        indexRequest.index("goods");
        // 将Java对象转换成JSON格式
        ObjectMapper mapper = new ObjectMapper();
        for (Goods goods1 : goodsList) {
            indexRequest.id(goods1.getId().toString());
            String jsongood = mapper.writeValueAsString(goods1);
            // 设置源数据和内容类型
            indexRequest.source(jsongood, XContentType.JSON);
            // 发送请求，添加数据
            IndexResponse response = client.index(indexRequest, RequestOptions.DEFAULT);
            System.out.println("添加数据的结果：" + response.getIndex());
        }
        //关闭连接
        client.close();
        return null;
    }

    @RequestMapping("findAll2")
    public Result<List<Good>> findAll2(Good good) throws IOException {
        // 从数据库获取数据
        List<Good> goods = goodMapper.findAll(good);
        System.out.println("1111111111111111111111111111"+goods);
        //创建java和es的链接
        HttpHost httpHost = new HttpHost("127.0.0.1", 9200, "http");
        RestClientBuilder builder = RestClient.builder(httpHost);
        RestHighLevelClient client = new RestHighLevelClient(builder);
        System.out.println(client.indices());
        //指令方式: put /good/_doc/1 {}
        IndexRequest indexRequest = new IndexRequest();
        // 创建IndexRequest并指定类型
        //IndexRequest indexRequest = new IndexRequest("your_index_name", "your_type_name");
        indexRequest.index("good");
        // 将Java对象转换成JSON格式
        ObjectMapper mapper = new ObjectMapper();
        for (Good good1 : goods) {
            indexRequest.id(good1.getId().toString());
            String jsongood = mapper.writeValueAsString(good1);
            // 设置源数据和内容类型
            indexRequest.source(jsongood, XContentType.JSON);
            // 发送请求，添加数据
            IndexResponse response = client.index(indexRequest, RequestOptions.DEFAULT);
            System.out.println("添加数据的结果：" + response.getIndex());
        }
        //关闭连接
        client.close();
        return null;
    }


    @RequestMapping("findAll3")
    public Result<List<Good>> findAll(Good good) throws IOException {

        // 从数据库获取数据
        List<Good> goods = goodMapper.findAll(good);

        // 创建java和es的链接
        HttpHost httpHost = new HttpHost("127.0.0.1", 9200, "http");
        RestClientBuilder builder = RestClient.builder(httpHost);
        try (RestHighLevelClient client = new RestHighLevelClient(builder)) {

            // 查询根据文档id某个文档对象  get /index/_doc/1
            GetRequest getRequest = new GetRequest().index("good").id("1");

            // 发送请求
            GetResponse response = client.get(getRequest, RequestOptions.DEFAULT);

            // 输出响应结果
            System.out.println("_index:" + response.getIndex());
            System.out.println("_id:" + response.getId());
            System.out.println("_type:" + response.getType());
            String asString = response.getSourceAsString();
            System.out.println("对象数据:" + asString);

            // 封装结果
            Result<List<Good>> result = Result.success(goods, "数据获取成功");

            return result;
        }
    }

}
